package com.tx;

import com.utils.DBUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;

@Component
@Aspect
public class TxManager {

    //这里使用before、after或者around 都可以
    //回滚:AfterThrowing

    //真正做开发 第一版--->一般写的都非常的烂...不断地重构/调整--->优雅的代码

    @Pointcut("execution(* com.service.BuyService.*(..))")
    public void txRule(){

    }

    @Around("txRule()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
        Connection conn = DBUtils.getConn();
        conn.setAutoCommit(false);//设置不自动提交

        Object ret = joinPoint.proceed();

        conn.commit();//提交
        return ret;
    }

    @AfterThrowing(value = "txRule()",throwing = "ex")
    public void afterThrowing(Exception ex){
        try {
            System.out.println("执行回滚....");
            DBUtils.conn.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            DBUtils.close();
        }
    }

}
